<template>
  <div>
    <el-dialog
      class="add_dialog"
      width="600px"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="100px"
      >
        <el-form-item
          label="角色名称:"
          prop="title"
        >
          <el-input
            v-model="form.title"
            maxlength="10"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色授权:">
          <div class="menu_wrapper">
            <el-tree
              :data="menuData"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              check-strictly
              @check-change="checkChange"
              @check="checkClick"
            >
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="dialogVisible = false"
        >取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submit"
        >保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addGroup, editGroup } from "@/api/system";
export default {
  props: ["editItem", "menuData"],
  data() {
    return {
      dialogVisible: false,
      form: {
        title: "",
        rules: ""
      },
      rules: {
        title: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.editItem ? "编辑角色" : "添加角色";
    }
  },
  methods: {
    checkClick(data, checkObj) {
      const check = checkObj.checkedKeys.indexOf(data.id) > -1;
      // 如果有子节点，勾选子节点
      if (check && data.children) {
        this.checkChildren(data.children);
      }
    },
    checkChange(data, check) {
      // 父节点操作
      if (data.pid != 0) {
        if (check === true) {
          // 如果选中，设置父节点为选中
          this.$refs.tree.setChecked(data.pid, true);
        } else {
          // 如果取消选中，检查父节点是否该取消选中（可能仍有子节点为选中状态）
          let parentNode = this.$refs.tree.getNode(data.pid);
          let parentHasCheckedChild = false;
          for (
            let i = 0, parentChildLen = parentNode.childNodes.length;
            i < parentChildLen;
            i++
          ) {
            if (parentNode.childNodes[i].checked === true) {
              parentHasCheckedChild = true;
              break;
            }
          }
          if (!parentHasCheckedChild)
            this.$refs.tree.setChecked(data.pid, false);
        }
      }
      // 子节点操作，如果取消选中，取消子节点选中
      if (data.children != null && check === false) {
        for (var j = 0, len = data.children.length; j < len; j++) {
          var childNode = this.$refs.tree.getNode(data.children[j].id);
          if (childNode.checked === true) {
            this.$refs.tree.setChecked(childNode.data.id, false);
          }
        }
      }
    },
    checkChildren(childList) {
      for (let item of childList) {
        this.$refs.tree.setChecked(item.id, true);
        if (item.children) {
          this.checkChildren(item.children);
        }
      }
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let selectList = this.$refs.tree.getCheckedKeys();
          if (selectList.length === 0) {
            this.$message({
              message: "角色授权不能为空",
              type: "warning"
            });
          } else {
            this.form.rules = selectList.join(',');
            if (this.editItem) {
              editGroup(this.form).then(res => {
                this.dialogVisible = false;
                this.$emit("getList");
              })
            } else {
              addGroup(this.form).then(res => {
                this.dialogVisible = false;
                this.$emit("getList");
              })
            }
          }
        } else {
          this.$message({
            message: "请检查表单错误",
            type: "error"
          });
          return false;
        }
      });
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs['form'].resetFields();
          if (this.editItem) {
            // 编辑
            this.form.id = this.editItem.id;
            this.form.title = this.editItem.title;
            this.form.rules = this.editItem.rules;
            const list = this.editItem.rules.split(',');
            this.$refs.tree.setCheckedKeys(list);
          }
        });
      } else {
        this.$refs.tree.setCheckedKeys([]);
        this.form = {
          title: "",
          rules: ""
        };
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.menu_wrapper {
  width: 400px;
  height: 400px;
  overflow: auto;
  border: 1px solid #eeeeee;
  padding: 10px;
}
</style>
